import useAdvancement from "@/hooks/useAdvancement";
import { AstroError } from "astro/errors";
import getRequire from "./getRequire";
import type { AdvancementDisplay } from "@/types/advancement";
import useIcon from "@/hooks/useIcon";
import getTranslateByKey from "@/utils/getTranslateByKey";
import getAdvancementTitle from "./getAdvancementTitle";
import type { Props as TrProps } from '../components/Tr.astro'
import { AdvancementsOverwrite } from "../constants";

export function getAdvancements(ids: string[]) {
  return Promise.all(ids.map((id) => getAdvancement(id)));
}

export default async function getAdvancement(name: string, version?: string, require?: string): Promise<TrProps> {
  const advancement = useAdvancement(name, version);

  if (!advancement) {
    throw new AstroError("无法找到该成就相关文件：" + name);
  }

  let OverwriteResult =
    AdvancementsOverwrite[name as keyof typeof AdvancementsOverwrite]
  if (typeof OverwriteResult == "string")
    OverwriteResult = { require: OverwriteResult };

  const { id, parent = "", display = {}, criteria } = advancement;

  const FinalRequire = require ? require : getRequire(criteria);

  const {
    icon: { item },
    title: { translate: title },
    description: { translate: description },
    frame = "task",
  } = display as AdvancementDisplay;

  const { smallIcon } = useIcon(item)!;

  const cnTitle = await getTranslateByKey(title),
    enTitle = await getTranslateByKey(title, "en_us"),
    cnDescription = await getTranslateByKey(description);

  return Object.assign({
    id,
    icon: smallIcon,
    frame,
    title: cnTitle,
    enTitle,
    parent: parent.length ? await getAdvancementTitle(parent) : undefined,
    description: cnDescription,
    require: FinalRequire,
  }, OverwriteResult);
}